using Godot;
using System;

public partial class ExperienceVial : Node2D
{

	GameEvents gameEvents;
	CollisionShape2D collisionShape2D;
	Sprite2D sprite;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		gameEvents = GetNode<GameEvents>("/root/GameEvents");
		collisionShape2D = GetNode<CollisionShape2D>("Area2D/CollisionShape2D");
		sprite = GetNode<Sprite2D>("Sprite2D");
		GetNode<Area2D>("Area2D").AreaEntered += (otherArea) =>
		{
			this.OnAreaEntered(otherArea);
		};
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

	public void TweenCollect(float percent, Vector2 startPosition)
	{
		Node2D player = GetTree().GetFirstNodeInGroup("player") as Node2D;
		if (player == null){
			return;
		}
		GlobalPosition = startPosition.Lerp(player.GlobalPosition,percent);
		Vector2 directionFromStart  = player.GlobalPosition - startPosition;
		float targetRotation = directionFromStart.Angle() + Mathf.DegToRad(90);
		Rotation = Mathf.LerpAngle(Rotation,targetRotation,(float)(1 - Math.Exp(-2 * GetProcessDeltaTime())));
	}
	
	public void Collect(){
		gameEvents.EmitExperienceVialCollected(1);
		QueueFree();
	}

	public void DisableCollision(){
		collisionShape2D.Disabled = true;
	}

	public void OnAreaEntered(Area2D otherArea)
	{
		Callable callable = Callable.From(DisableCollision);
		callable.CallDeferred();

		Tween tween = CreateTween();
		tween.SetParallel();
		Vector2 currentPosition = GlobalPosition;
		tween.TweenMethod(Callable.From((float percent) => { TweenCollect(percent, currentPosition); }), 0.0, 1.0, 0.5)
			.SetEase(Tween.EaseType.In)
			.SetTrans(Tween.TransitionType.Back);
		tween.TweenProperty(sprite,"scale",Vector2.Zero,.05).SetDelay(.45);
		tween.Chain();
		tween.TweenCallback(Callable.From(Collect));

		GetNode<RandomStreamPlayer2dComponent>("RandomStreamPlayer2DComponent").PlayRandom();
	}
}
